// pages/homework/supplementAnswer/supplementAnswer.js
import https from '../../../utils/request4.js'
import https7 from '../../../utils/request7.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    automatic: 1,
    modeType: 1,
    textValue: null,
    examcourseId: null,
    selectQuestion: {},
    option: null,
    multipleChoices: false,
    options: [],
    questionList: [],
    publishData: [],
    errorList: [],
    errorFlag: false,
    waringList: [],
    waringFlag: false,
    identificationFlag: false,
    name: null,
    targetId: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
      this.setData({
        examcourseId: options.examCourseId,
        name: options.name
      })
      this.getInfo()
  },
  async getInfo() {
        let options={
            url:`/system/card/question/info?id=${this.data.examcourseId}`,
            method:'get',
            header:{"content-type":"application/json;charset=UTF-8"}
        }
        let res = await https7(options)
        if(res&&res.data.code==200){
            if (res.data.data.length == 0) {
                // wx.showToast({
                //     title: '本张试卷不需要补充答案',
                //     icon: 'none',
                //     duration: 1000 //持续的时间
                // })
                wx.showModal({
                    title: '提示',
                    content: '本张试卷不需要补充答案',
                    showCancel: false,
                    success: (res) => {
                      if (res.confirm) {
                        console.log('用户点击确定')
                        wx.redirectTo({
                            url: '/pages/homework/homeworkSituation/homeworkSituation?flag=2'
                        })
                      }
                    }
                })
            }
            res.data.data.map(ress => {
                if (ress.questionType == 3) {
                    ress.optionList = ['T','F']
                } else {
                    let optionList = []
                    for(var i = 0;i < ress.optionCount; i++) {
                        optionList.push(this.numberToLetter(i))
                    }
                    ress.optionList = optionList
                }
            })
            this.setData({
                questionList: res.data.data
            })
            if (res.data.data.length > 0) {
                this.setData({
                    name: res.data.data[0].cardName,
                })
            }
            const result = res.data.data.find(item => {
                return (item.answer == "" || item.answer == null)
            })
            console.log(result,'11111111111')
            if (result != undefined) {
                this.setData({
                    selectQuestion: result
                })
            } else {
                this.setData({
                    selectQuestion: res.data.data[0]
                })
                if (res.data.data[0].questionType == 1 || res.data.data[0].questionType == 4) {
                    // 多选
                    this.setData({
                        options: res.data.data[0].answer.split('')
                    })
                } else {
                    this.setData({
                        option: res.data.data[0].answer
                    })
                }
            }
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
  },
  cancel() {
    this.setData({
        errorFlag: false,
        errorList: [],
        waringList: [],
        waringFlag: false
    })
  },
  testPublish() {
        let data = []
        let errorList = []
        let waringList = []
        console.log(this.data.questionList,'---------');
        this.data.questionList.map(res => {
            // if (res.answer == '' || res.answer == null || res.answer == undefined) {
            //     errorList.push(res)
            // } else {
            //     if (res.questionType == 2 || res.questionType == 4) {
            //         if (res.answer.length == 1) {
            //             waringList.push(res)
            //         }
            //     }
            // }
            data.push({
                id: res.id,
                answer: res.answer?res.answer:''
            })
        })
        this.setData({
            publishData: data
        })
        this.publish()
        // if (errorList.length > 0) {
        //     // 有异常
        //     this.setData({
        //         errorList:errorList,
        //         errorFlag: true
        //     })
        // } else if (waringList.length > 0) {
        //     // 有轻微异常，可提交，但是需要提示
        //     this.setData({
        //         waringList:waringList,
        //         waringFlag: true
        //     })
        // } else {
        //     this.publish()
        // }
  },
  // 发布
  async publish() {
      console.log(this.data.publishData,'11111111111111111111111');
      let data = {
        cardId: this.data.examcourseId,
        questionAnswerInputList: this.data.publishData
      }
        let options={
            url:`/system/card/follow/answer`,
            method:'post',
            data:data,
            header:{"content-type":"application/json;charset=UTF-8"}
        }
        let res = await https7(options)
        if(res&&res.data.code==200){
            wx.redirectTo({
                url: '/pages/homework/homeworkSituation/homeworkSituation?flag=2'
            })
        } else {
            wx.showToast({
                title: res.data.message,
                icon: 'none',
                duration: 2000 //持续的时间
            })
        }
  },
  numberToLetter(num) {
    return String.fromCharCode(num + 65);
  },
  checkboxChange(e) {
      console.log(e.detail.value);
    this.setData({
        automatic: e.detail.value.length > 0 ? 0 : 1
    })
  },
  chooseOption(e) {
    if (this.data.automatic == 0) {
        // 直接赋值并提交
        this.setData({
            option: e.currentTarget.dataset.index
        })
        this.submit()
    } else {
        // 赋值
        this.setData({
            option: e.currentTarget.dataset.index
        })
    }
  },
  chooseOptions(e) {
      let options = this.data.options
      if (options.includes(e.currentTarget.dataset.index)) {
        let i = options.indexOf(e.currentTarget.dataset.index)
        options.splice(i,1)
      } else {
        options.push(e.currentTarget.dataset.index)
      }
      this.setData({
          options: options
      })
      console.log(options,'9999999999999');
  },
  submit() {
    // 提交并跳转下一题
    let questionList = this.data.questionList
    if (this.data.selectQuestion.questionType == 1 || this.data.selectQuestion.questionType == 3) {
        // 单选
        questionList.map(res => {
            if (res.id == this.data.selectQuestion.id) {
                res.answer = this.data.option
                this.setData({
                    option: null
                })
            }
        })
    } else {
        // 多选
        questionList.map(res => {
            if (res.id == this.data.selectQuestion.id) {
                res.answer = this.data.options.join('')
                this.setData({
                    options: []
                })
            }
        })
    }
    this.setData({
        questionList: questionList,
        targetId: 'section' + this.data.selectQuestion.id
    })
    console.log(this.data.targetId,'++++++++++++++++++++++')
    const result = questionList.find(item => {
        return (item.answer == "" || item.answer == null)
    })
    console.log(questionList,result,'-------------');
    if (result != undefined) {
        this.setData({
            selectQuestion: result
        })
        console.log(this.data.selectQuestion,'9999999999999999000000000000')
    } else {
        this.setData({
            selectQuestion: questionList[0],
        })
        if (questionList[0].questionType == 1 || questionList[0].questionType == 4) {
            // 多选
            this.setData({
                options: questionList[0].answer.split('')
            })
        } else {
            this.setData({
                option: questionList[0].answer
            })
        }
        wx.showToast({
            title: '所有答案均已录完，请检查答案是否正确',
            icon: 'none',
            duration: 2000 //持续的时间
        })
    }
    if (this.data.selectQuestion.questionType == 2 || this.data.selectQuestion.questionType == 4) {
        this.setData({
            automatic: 1,
            multipleChoices: true
        })
    } else {
        this.setData({
            multipleChoices: false
        })
    }
  },
  modeChange(e) {
    this.setData({
        modeType: e.currentTarget.dataset.value
    })
    if (e.currentTarget.dataset.value == 1) {
        let questionList = this.data.questionList
        const result = questionList.find(item => {
            return (item.answer == "" || item.answer == null)
        })
        if (result != undefined) {
            this.setData({
                selectQuestion: result
            })
        } else {
            this.setData({
                selectQuestion: questionList[0],
            })
            if (questionList[0].questionType == 1 || questionList[0].questionType == 4) {
                // 多选
                this.setData({
                    options: questionList[0].answer.split('')
                })
            } else {
                this.setData({
                    option: questionList[0].answer
                })
            }
        }
        if (this.data.selectQuestion.questionType == 2 || this.data.selectQuestion.questionType == 4) {
            this.setData({
                automatic: 1,
                multipleChoices: true
            })
        } else {
            this.setData({
                multipleChoices: false
            })
        }
    }
  },
  identification() {
    try {
        let str = this.processText(this.data.textValue)
        let arr = this.splitString(str)
        console.log(arr,'---------======================------------');
        let questionList = this.data.questionList
        questionList.map((res,index) => {
            res.answer = arr[index]
        })
        this.setData({
            questionList: questionList,
            identificationFlag: true
        })

    } catch (error) {
        console.error(error.message);
    }
  },
  questionSelect(e) {
    this.setData({
        selectQuestion: e.currentTarget.dataset.item
    })
    if (e.currentTarget.dataset.item.questionType == 2 || e.currentTarget.dataset.item.questionType == 4) {
        this.setData({
            automatic: 1,
            multipleChoices: true
        })
    } else {
        this.setData({
            multipleChoices: false
        })
    }
    if (e.currentTarget.dataset.item.answer == "" || e.currentTarget.dataset.item.answer == null) {
        this.setData({
            option: null,
            options: []
        })
    } else {
        // 判断是单选还是多选
        if (e.currentTarget.dataset.item.questionType == 2 || e.currentTarget.dataset.item.questionType == 4) {
            this.setData({
                option: null,
                options: e.currentTarget.dataset.item.answer.split('')
            })
        } else {
            this.setData({
                option: e.currentTarget.dataset.item.answer,
                options: []
            })
        }
    }
  },
  splitString(str) {
    // 核心思路：全局匹配所有括号内容和非括号内容
    const parts = str.split(/(\([^)]*\))/g); // 分割成 [非括号内容, 括号内容, 非括号内容...]
    const result = [];
  
    for (const part of parts) {
      if (!part) continue; // 跳过空片段
      if (part.startsWith('(') && part.endsWith(')')) {
        // 提取括号内的内容 (去掉首尾括号)
        result.push(part.slice(1, -1));
      } else {
        // 非括号部分拆分成单字符
        result.push(...part.split(''));
      }
    }
    return result.filter(c => c !== ''); // 过滤空字符
  },
  onTextInput(e) {
    this.setData({ textValue: e.detail.value });
  },
  processText(text) {
    // 校验规则：允许大小写字母、空格、中文括号、英文括号
    const allowedPattern = /^[A-Za-z\s（）()]*$/;
    
    // 校验失败处理
    if (!allowedPattern.test(text)) {
      // 提取非法字符（排除允许的字符）
      const illegalChars = [...new Set(text.match(/[^A-Za-z\s（）()]/g))];
      throw new Error(`文本包含非法字符: ${illegalChars.join(', ')}`);
    }
  
    // 校验通过后处理文本
    return text
      .replace(/（/g, '(')      // 中文左括号 → 英文左括号
      .replace(/）/g, ')')      // 中文右括号 → 英文右括号
      .toUpperCase()           // 转为全大写字母
      .replace(/\s+/g, '');    // 去除所有空格
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})